import json

import cx_Oracle
import requests
# cx_Oracle.init_oracle_client(lib_dir='/opt/oracle/instantclient_19_8', config_dir=None, error_url=None, driver_name=None)
from oracle_conn.ficus_put import ficus_put


def main():
    # 1.建立连接
    conn = cx_Oracle.connect('DI_JW', 'cent2012#edu', '202.115.47.134:1521/JW')

    # 2.创建游标
    cursor = conn.cursor()

    # 3.执行SQL
    res = cursor.execute('select * from newjw.code_bjb')
    title = [i[0] for i in cursor.description]

    # 4.获取数据
    res.fetchmany(100)
    while True:
        data = res.fetchmany(100)
        if not data:
            break
        print(len(data))
        print(data)

        url = 'http://10.3.1.147:30078/sobeyficus/v1/restcrawl/S1/scu20201124/yfwla8e347186983'
        token = '052134b0-0f94-40d3-b9c5-ca0ca65c7070'
        ficus_put(url, token, title, data)

    # 5.关闭游标
    cursor.close()

    # 6.关闭连接
    conn.close()


def table_rol_num(table_name):
    conn = cx_Oracle.connect('DI_JW', 'cent2012#edu', '202.115.47.134:1521/JW')
    cursor = conn.cursor()
    res = cursor.execute(f'select * from newjw.{table_name}')
    title = [i[0] for i in cursor.description]
    print(title)
    print(res.fetchmany(1))


def table_data(table_name, url, token):
    try:
        conn = cx_Oracle.connect('DI_JW', 'cent2012#edu', '202.115.47.134:1521/JW')
        cursor = conn.cursor()
        res = cursor.execute(f'select * from newjw.{table_name}')
        title = [i[0] for i in cursor.description]

        while True:
            data = res.fetchmany(100)
            if not data:
                break
            ficus_put(url, token, title, data)

    except cx_Oracle.DatabaseError as exp:
        print(table_name, exp.args)
        with open('jw_error.txt', 'a') as f:
            f.write(f'{table_name}-{exp.args}')
    except Exception as exp:
        print(table_name, exp.args)
        with open('jw_error.txt', 'a') as f:
            f.write(f'{table_name}-{exp.args}')


def anay_jw(file_name):
    with open(file_name, 'r') as f:
        data = f.readlines()
    for l in data:
        table_name, url, token = tuple(l.split())
        print(table_name)
        url = 'http://10.3.1.147:30078' + url
        table_data(table_name, url, token)


if __name__ == '__main__':
    anay_jw('jw_url1.txt')
    # table_rol_num('code_kcb')